package com.example.util.handler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-09 19:11
 **/
public class BeanHandler<T> implements ResultSetHandler<T> {
    //查出一条记录
    private Class<T> beanClass;

    public BeanHandler(Class<T> beanClass) {
        this.beanClass = beanClass;
    }

    @Override
    public T handler(ResultSet rs) {
        T bean = null;
        try {

            bean = beanClass.getConstructor().newInstance();
            if (rs.next()) {
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    //    得到列名
                    String columnName = rsmd.getColumnName(i);
                    //通过列名获取数据
                    Object colunmValue = rs.getObject(columnName);
                    //6.6列名其实就是对象中成员的名称,
                    //对象属性的描述器
                    PropertyDescriptor pd = new PropertyDescriptor(columnName.toLowerCase(), beanClass);
                    Method writeMethod = pd.getWriteMethod();
                    writeMethod.invoke(bean, colunmValue);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return bean;
    }
}
